package com.baiyinet.ui.main;

import android.annotation.SuppressLint;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.baiyinet.R;
import com.baiyinet.util.CookieHelper;
import com.baiyinet.util.webview.GeneralWebViewClient;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * Created by developer on 18-2-1.
 */

@EFragment(R.layout.frag_common_web)
public class CommonWebFragment extends Fragment {

    @FragmentArg("url")
    String url;

    @ViewById(R.id.frag_common_layout_container)
    LinearLayout mLayout;
    private WebView mWebView;
    private WebSettings mWebSettings;

    @AfterViews
    void initView() {
        mWebView = new WebView(getActivity().getApplicationContext());
        mWebSettings = mWebView.getSettings();

        enableJavaScript();
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setSupportZoom(false);
        mWebSettings.setUseWideViewPort(false);
        mWebSettings.setBuiltInZoomControls(false);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);

        if(Build.VERSION.SDK_INT >= 19) {
            mWebSettings.setLoadsImagesAutomatically(true);
        } else {
            mWebSettings.setLoadsImagesAutomatically(true);
        }

        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebSettings.setPluginState(WebSettings.PluginState.ON);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setDefaultTextEncodingName("UTF-8");
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDatabaseEnabled(false);
        // 取消网页记住密码
        mWebSettings.setSavePassword(false);
        mWebSettings.setSaveFormData(false);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (Build.VERSION.SDK_INT >= 21) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.clearFormData();
        mWebView.clearHistory();
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setVerticalScrollBarEnabled(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mWebView.setBackgroundColor(Color.argb(1, 0, 0, 0));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (0 != (getActivity().getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }

        mLayout.addView(mWebView);

        loadUrl();
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
        enableJavaScript();
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mWebView.stopLoading();
        disableJavaScript();
    }

    @Override
    public void onDestroy() {
        destroy();
        super.onDestroy();
    }

    public void destroy() {
        mWebSettings = null;
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            // 释放资源
            mWebView.destroy();
            mWebView = null;
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (mWebView != null) {
                if (TextUtils.isEmpty(mWebView.getUrl())) {
                    loadUrl();
                }
            }
        }
    }

    public void loadUrl() {

        mWebView.setWebViewClient(new GeneralWebViewClient(getActivity(), null, url, mWebView, null, ((MainActivity)getActivity()).getCurrentUser(), ((MainActivity)getActivity()).getApiHelper()));

        CookieHelper.setWebViewRequestUrlCookie(getActivity(), url, ((MainActivity)getActivity()).mCurrentUser.getCurrentCookie());

        Map<String, String> cookies = new WeakHashMap<>();
        cookies.put("AppOS", "Android");

        if (!url.startsWith("javascript")) {
            mWebView.clearView();
        }
        mWebView.loadUrl(url, cookies);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void enableJavaScript(){
        mWebSettings.setJavaScriptEnabled(true);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void disableJavaScript() {
        mWebSettings.setJavaScriptEnabled(false);
    }

}
